Linux: Inject html fragments with NGINX
Last update: 5/5/2019, 3:44:23 PM
Wouldn't it be great to be able to insert html fragments to a page just before serving them? One use case that comes to mind is adding an analytics script. The good news is that this is possible with the swiss army knive of webservers - NGINX.
Example of adding a fragment to the bottom of the <body>
of a page.
sub_filter '</body>' '<your fragment></body>';
sub_filter_once on;
Note that this code depends on the ngx_http_sub_module
to be loaded. On Ubuntu distros this module is enabled by default
See: https://nginx.org/en/docs/http/ngx_http_sub_module.html